const mongoose = require('mongoose');

const orderSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, '工单标题不能为空'],
    trim: true,
    maxlength: [100, '工单标题不能超过100个字符']
  },
  description: {
    type: String,
    required: [true, '工单描述不能为空'],
    trim: true,
    maxlength: [1000, '工单描述不能超过1000个字符']
  },
  type: {
    type: String,
    required: [true, '工单类型不能为空'],
    enum: {
      values: ['repair', 'maintenance', 'installation', 'other'],
      message: '工单类型只能是 repair、maintenance、installation 或 other'
    }
  },
  status: {
    type: String,
    enum: {
      values: ['waiting', 'processing', 'waitingPayment', 'completed', 'cancelled', 'evaluating', 'evaluated'],
      message: '工单状态无效'
    },
    default: 'waiting'
  },
  urgency: {
    type: String,
    enum: {
      values: ['low', 'medium', 'high', 'urgent'],
      message: '紧急程度只能是 low、medium、high 或 urgent'
    },
    default: 'medium'
  },
  
  // 用户信息
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: [true, '用户ID不能为空']
  },
  userName: {
    type: String,
    required: [true, '用户姓名不能为空']
  },
  userPhone: {
    type: String,
    required: [true, '用户手机号不能为空']
  },
  userAddress: {
    type: String,
    required: [true, '用户地址不能为空'],
    maxlength: [200, '用户地址不能超过200个字符']
  },
  
  // 维修人员信息
  maintainerId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    default: null
  },
  maintainerName: {
    type: String,
    default: ''
  },
  maintainerPhone: {
    type: String,
    default: ''
  },
  
  // 时间信息
  assignedAt: {
    type: Date,
    default: null
  },
  startedAt: {
    type: Date,
    default: null
  },
  completedAt: {
    type: Date,
    default: null
  },
  
  // 服务信息
  serviceFee: {
    type: Number,
    min: [0, '服务费用不能为负数'],
    default: 0
  },
  serviceDescription: {
    type: String,
    maxlength: [500, '服务描述不能超过500个字符'],
    default: ''
  },
  
  // 评价信息
  rating: {
    type: Number,
    min: [1, '评分不能低于1'],
    max: [5, '评分不能高于5'],
    default: null
  },
  feedback: {
    type: String,
    maxlength: [500, '反馈不能超过500个字符'],
    default: ''
  },
  
  // 附件信息
  images: [{
    type: String,
    validate: {
      validator: function(v) {
        return v.length <= 10;
      },
      message: '图片数量不能超过10张'
    }
  }],
  documents: [{
    type: String,
    validate: {
      validator: function(v) {
        return v.length <= 5;
      },
      message: '文档数量不能超过5个'
    }
  }],
  
  // 备注信息
  notes: {
    type: String,
    maxlength: [500, '备注不能超过500个字符'],
    default: ''
  },
  adminNotes: {
    type: String,
    maxlength: [500, '管理员备注不能超过500个字符'],
    default: ''
  },
  
  // 工单编号（自动生成）
  orderNumber: {
    type: String
  }
}, {
  timestamps: true,
  versionKey: false
});

// 生成工单编号的中间件
orderSchema.pre('save', async function(next) {
  if (this.isNew && !this.orderNumber) {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    // 查找当天的最后一个工单号
    const datePrefix = `WO${year}${month}${day}`;
    const lastOrder = await this.constructor.findOne({
      orderNumber: new RegExp(`^${datePrefix}`)
    }).sort({ orderNumber: -1 });
    
    let sequence = 1;
    if (lastOrder && lastOrder.orderNumber) {
      const lastSequence = parseInt(lastOrder.orderNumber.slice(-4));
      sequence = lastSequence + 1;
    }
    
    this.orderNumber = `${datePrefix}${String(sequence).padStart(4, '0')}`;
  }
  next();
});

// 状态变更时更新时间戳
orderSchema.pre('save', function(next) {
  const now = new Date();
  
  if (this.isModified('status')) {
    switch (this.status) {
      case 'processing':
        if (!this.startedAt) this.startedAt = now;
        break;
      case 'completed':
        if (!this.completedAt) this.completedAt = now;
        break;
    }
  }
  
  if (this.isModified('maintainerId') && this.maintainerId && !this.assignedAt) {
    this.assignedAt = now;
  }
  
  next();
});

// 创建索引
orderSchema.index({ userId: 1 });
orderSchema.index({ maintainerId: 1 });
orderSchema.index({ status: 1 });
orderSchema.index({ type: 1 });
orderSchema.index({ urgency: 1 });
orderSchema.index({ createdAt: -1 });
orderSchema.index({ orderNumber: 1 }, { unique: true });

// 复合索引
orderSchema.index({ status: 1, createdAt: -1 });
orderSchema.index({ userId: 1, status: 1 });
orderSchema.index({ maintainerId: 1, status: 1 });

module.exports = mongoose.model('Order', orderSchema);